﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using System.Xml.Linq;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.Screenr
{
    public class ScreenrService
    {
        private ScreenrConfig _config;

        public ScreenrService(string config)
        {
            _config = config.DeserializeJsonTo<ScreenrConfig>();
        }

        public ScreenrConfig Config
        {
            get { return _config; }
        }

        public IList<ScreenrVideo> GetVideos()
        {
            var feed = XDocument.Load("http://screenr.com/user/" + _config.Username.ToLower() + "/rss");

            return (from item in feed.Descendants("item")
                    select GetVideo(item.Element("link").Value)).ToList();
        }

        public ScreenrVideo GetVideo(string url)
        {
            var item = XDocument.Load("http://screenr.com/api/oembed.xml?url=" + url);
            return new ScreenrVideo
            {
                Link = url,
                Title = item.Root.Element("title").Value,
                Author = item.Root.Element("author_name").Value,
                Width = Convert.ToInt32(item.Root.Element("width").Value),
                Height = Convert.ToInt32(item.Root.Element("height").Value),
                EmbedCode = item.Root.Element("html").Value
            };
        }
    }

    #region Model
    
    public class ScreenrVideo
    {
        public string Link { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public string EmbedCode { get; set; }
    }

    #endregion
}